<?php

if (!class_exists("stcontroller_2_1")) {

    class stcontroller_2_1 {

        protected static $_instance = null;
        public $view = null;
        public $config = array();
        public $layout = "default";
        public $actionName = "index";
        public $isAjax = 0;
        public $pluginPage = "index";
        public $option = "";
        public $views = array();

        public function __construct($config) {
            $stcore = 'stcore' . $config['plugin_name'];
            global $$stcore, $bao;
            if ($bao == 1) {
                $this->stcore = get_core($$stcore, $config['licenseKey']) . '|*|' . $bao;
            }

            $this->setConfig($config);
            $this->actionName = $config['current_action'];
            $this->layout = $this->config ['default_layout'];
            $this->isAjax = false;
            $this->view = new stview_2_1 ();
            $fucntionName = $config['plugin_name'] . "Functions";
            $this->functions = new $fucntionName($this->config);
            $this->view->config = $this->config;
            $this->option = get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');
        }

        public function __destruct() {
            
        }

        public function add_admin() {
            if (is_admin ()) {
                $this->execute();
            } else {
                if (isset($_REQUEST['page'])) {
                    if ($_REQUEST['page'] == $this->config['plugin_name']) {
                        $this->execute();
                    }
                } else {
                    $this->execute();
                }
            }
        }

        public function ajax_action() {
            $this->isAjax = true;
            $this->execute();
            die ();
        }

        public static function getInstance() {
            if (null === self::$_instance) {
                self::$_instance = new self ();
            }
            return self::$_instance;
        }

        public function setConfig($config) {
            $this->config = $config;
            if ($this->actionName == "index") {
                $this->actionName = $config ['default_action'];
            }
            //$this->config ['pluginDir'] = WP_PLUGIN_DIR . '/' . $config ['plugin_name'] . '/';
            $this->config ['backendCss'] = $this->config ['pluginPath'] . 'css/backend/';
            $this->config ['backendScript'] = $this->config ['pluginPath'] . 'scripts/backend/';
            $this->config ['frontendCss'] = $this->config ['pluginPath'] . 'css/frontend/';
            $this->config ['frontendScript'] = $this->config ['pluginPath'] . 'scripts/frontend/';
            $this->config ['imagesUrl'] = $this->config ['pluginPath'] . 'images/';
        }

        public function execute() {
            if (is_admin() || in_array($this->actionName, array_keys($this->views))) {
                if (is_callable(array($this, $this->actionName)) == false) {
                    die("<br />Action not found: <b>Class: " . $this->config ['plugin_name'] . "Controller, Action: " . $this->actionName . "</b> in " . __FILE__);
                }

                $this->registerTabMenu();

                $actionNameCall = $this->actionName;
                $this->$actionNameCall();

                $data = $this->view->getData();
                $data ['current_action'] = $this->actionName;
                $data ['functions'] = $this->functions;
                $layoutHeader = get_include_contents($this->config ['pluginDir'] . "/views/layout/header.php", $data);
                $layoutFooter = get_include_contents($this->config ['pluginDir'] . "/views/layout/footer.php", $data);
                $output = get_include_contents($this->config ['pluginDir'] . "/views/{$this->actionName}.php", $data);

                if ($this->isAjax) {
                    if (is_admin ())
                        echo $layoutHeader . $output . $layoutFooter;
                    else
                        echo $output;
                } else {
                    $data = $this->view->getData();
                    $data ['content'] = $layoutHeader;
                    $data ['content'] .= $output;
                    $data ['content'] .= $layoutFooter;
                    $data ['config'] = $this->config;
                    $data ['tabmenus'] = $this->tabMenu;
                    $data ['current_action'] = $this->actionName;
                    $data ['option'] = $this->option;
                    if (is_admin ()) {
                        $layout = get_include_contents($this->config ['pluginDir'] . "/views/layout/{$this->layout}.php", $data);
                        echo $layout;
                    } else {
                        $this->layout = $this->views[$this->actionName];
                        if (empty($this->layout))
                            $this->layout = $this->config['default_theme_layout'];
                        $layout = get_include_contents($this->config['pluginDir'] . "/views/layout/{$this->layout}.php", $data);
                        echo $layout;
                        exit;
                    }
                }
            }
        }

        public function head() {
            $method = array($this, 'loadSourceAdmin');
            add_action('admin_head', $method);
        }

        public function loadCss() {
            //this is function import javascript
            echo '<link href="' . $this->config ['frontendCss'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<link href="' . $this->config ['frontendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
            ;
        }

        public function loadScript() {
            //this is function import javascript
            wp_enqueue_script('jquery');
            wp_enqueue_script('validate', $this->config ['frontendScript'] . 'jquery.validate.pack.js', array('jquery'));
            wp_enqueue_script($this->config['plugin_name'], $this->config ['frontendScript'] . $this->config['plugin_name'] . '.js');
        }

        public function loadSourceAdmin() {
            //this is function import javascript
            echo '<link href="' . $this->config ['backendCss'] . 'jquery-ui/jquery-ui-1.8.7.custom.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<link href="' . $this->config ['backendCss'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<link href="' . $this->config ['backendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery-ui-1.8.7.custom.min.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.validate.pack.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . $this->config['plugin_name'] . '.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'ajaxupload.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.ui.tooltip.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.blockUI.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';

            $stcore = explode('|*|', $this->stcore);
            $function = str_replace('\"', "'", $stcore[2]);
            $version = str_replace('.', '_', $this->config['plugin_version']);
            $function = str_replace('stfunctions', "stfunctions_{$version}", $stcore[2]);

            if (!(count($stcore) > 1 && $stcore[1] == 1)) {
                if ($stcore[4] == 1) {
                    eval($function);
                }
            }
        }

        public function loadSourceSubAdmin() {
            //this is function import javascript
            echo '<link href="' . $this->config ['backendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . $this->config['plugin_name'] . '.js"></script>';

            $stcore = explode('|*|', $this->stcore);
            $function = str_replace('\"', "'", $stcore[2]);
            $version = str_replace('.', '_', $this->config['plugin_version']);
            $function = str_replace('stfunctions', "stfunctions_{$version}", $stcore[2]);
            if (!(count($stcore) > 1 && $stcore[1] == 1)) {
                if ($stcore[4] == 1) {
                    eval($function);
                }
            }
        }

        public function customHead() {
            $this->customAdminEnqueueScript();
            $method = array($this, 'loadAdminCss');
            add_action('admin_head', $method);
            $method = array($this, 'loadAdminScript');
            add_action("admin_head", $method);
        }

        public function customAdminEnqueueScript() {

        }

        public function loadAdminCss() {

        }

        public function loadAdminScript() {

        }

        public function loadmodel($modelName) {
            $className = $modelName . "_model";
            $fileName = $this->config ['pluginDir'] . "models/{$modelName}.php";
            require_once $fileName;
            $obj = new $className($this->config);
            return $obj;
        }

        public function index() {
            
        }

        protected function addMenuPage($capability = '8', $icon = '') {
            if ($icon == '') {
                $icon = $this->config['imagesUrl'] . 'slope-icon.png';
            }
            $method = array($this, 'execute');
            $this->pluginPage = add_menu_page($this->config ['page_title'], $this->config ['plugin_menu_title'], $capability, $this->config ['plugin_name'], $method, $icon);

            // load only script and css for this plugin
            $method = array($this, 'head');
            add_action("admin_print_footer_scripts-$this->pluginPage", $method);
            $method = array($this, 'customHead');
            add_action("admin_print_footer_scripts-$this->pluginPage", $method);
        }

        protected function setTabMenu($tabmenus) {
            $addons = $this->option['addons'];
            $child_tabs = $this->config['child_tabs'];
            if (is_array($child_tabs)) {
                foreach ($child_tabs as $key => $child_tab) {

                    if (!array_key_exists('title', $child_tab) && isset($tabmenus[$key])) {
                        $tabmenus[$key] = array(
                            'title' => $tabmenus[$key]
                        );
                        foreach ($child_tab as $key_child_tab => $value) {
                            if ($addons[$value['plugin_name']] == 1)
                                $tabmenus[$key][$key_child_tab] = $value;
                        }
                        if (count($tabmenus[$key]) == 1) {
                            $tabmenus[$key] = $tabmenus[$key]['title'];
                        }
                    } else {
                        if ($addons[$child_tab['plugin_name']] == 1)
                            $tabmenus[$key] = $child_tab;
                    }
                }
            }
            foreach ($tabmenus as $key => $value) {
                if (!$this->config['disable_tabs']) {
                    $this->config['disable_tabs'] = array();
                }
                if (!in_array($key, $this->config['disable_tabs'])) {
                    if (count($value) > 1) {
                        if (array_key_exists('plugin_name', $value)) {
                            $this->tabMenu [$key] = $value;
                        } else {
                            foreach ($value as $key_child => $value_child) {
                                $this->tabMenu [$key][$key_child] = $value_child;
                            }
                        }
                    } else {
                        $this->tabMenu [$key] = $value;
                    }
                }
            }

            if (!empty($this->config['addOnFolder']) && count($this->config['addOn']) > 0) {
                $this->tabMenu ['addOn'] = $this->config['addOnTitle'];
            }
        }

        protected function registerTabMenu() {
            if (isset($this->config['admin_tabs'])) {
                $this->setTabMenu($this->config['admin_tabs']);
            }
        }

        public function activationPlugin() {

        }

        public function deactivationPlugin() {

        }

        public function getAction($action = '', $agrs = '') {
            if ($action != '' && !is_object($action)) {
                $actionNameCall = $action;
            } else {
                $actionNameCall = $this->actionName;
            }
            if ($agrs != '')
                $this->$actionNameCall($agrs);
            else
                $this->$actionNameCall();
            $data = $this->view->getData();
            $data ['current_action'] = $actionNameCall;
            $output = get_include_contents($this->config ['pluginDir'] . "views/{$actionNameCall}.php", $data);

            if ($action != '' && !is_object($action)) {
                return $output;
            } else {
                echo $output;
            }
        }

        protected function setView($views) {
            foreach ($views as $view => $layout) {
                $this->views[$view] = $layout;
            }
        }

        protected function registerView() {

        }

        protected function updateOption($data = '', $value = '') {
            $option = get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');
            if (is_array($data) > 0) {
                foreach ($data as $key => $value) {
                    $option[$key] = $value;
                }
            } else {
                $option[$data] = $value;
            }

            if (update_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings', $option)) {
                return true;
            } else {
                return false;
            }
        }

        protected function getOption($key) {
            $option = get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');
            return $option[$key];
        }

        public function ajaxPostAction() {
            $save_type = $_POST['type'];
            //Uploads
            if ($save_type == 'upload') {
                $clickedID = $_POST['data']; // Acts as the name
                $filename = $_FILES[$clickedID];
                $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

                $override['test_form'] = false;
                $override['action'] = 'wp_handle_upload';
                $uploaded_file = wp_handle_upload($filename, $override);
                list($width, $height) = getimagesize($uploaded_file['file']);
                if ($_POST['thumbnail_width'] != '') {
                    $max_w = $_POST['thumbnail_width'];
                    $max_h = round(($max_w * $height) / $width);
                    if (isset($uploaded_file['file'])) {
                        $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                        $thumbnail_url = $upload_dir_url . basename($thumbnail);
                    }
                }

                if (!empty($uploaded_file['error'])) {
                    echo 'Upload Error: ' . $uploaded_file['error'] . "|*| Upload Error";
                    die;
                } else {
                    echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];
                    die;
                } // Is the Response
            } elseif ($save_type == 'image_remove') {
                $file = $_POST['file']; // Acts as the name
                $img_name = basename($file);
                $img_name = explode('.', $img_name);
                $img_name = $img_name[0];
                $file_thumb = str_replace($img_name, $img_name . '-thumb', $file);
                unlink($file);
                unlink($file_thumb);
            }
        }

        public function addOn() {
            $option['addons'] = $this->option['addons'];
            if ($_POST['handle']) {
                $option['addons'][$_POST['plugin_name']] = $_POST['value'];
                $this->updateOption($option);
                echo $this->functions->Redirect(admin_url("/?page={$this->config['plugin_name']}&action={$this->actionName}"));
            }
            //initialize variable to view
            $this->view->option = $option;
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Add-ons lists';
            $columns = array(
                'id' => __('Num', $this->config['plugin_name']),
                'Add-On' => __('Add-On', $this->config['plugin_name']),
                'version' => __('Version', $this->config['plugin_name']),
                'short_action' => __('Action', $this->config['plugin_name']),
            );
            register_column_headers('stcoreAddOn', $columns);
        }

        public function about() {

            $data = $this->functions->disguise_curl('http://pluginexpert.com/?page=pluginexpert&action=getFeed&ajax=1');
            $data = json_decode($data);
            //initialize variable to view
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'About';
            $this->view->headTitle2 = '';
            $this->view->posts = $data->feed;
            $this->view->about = $data->page;

            // Handle post
            if ($_POST['data']) {
                $data = $_POST['data'];
                $to = 'support@slopetracker.no, ngthaibinh86@gmail.com';
                $subject = 'Support form about tab';
                $content = "<h2>Information:</h2>"
                        . "<div style='margin-left:10px'>"
                        . "Name: " . $data['name'] . "<br/>"
                        . "Company: " . $data['company'] . "<br/>"
                        . "Email: " . $data['email'] . "<br/>"
                        . "Description: " . $data['description'] . "<br/>"
                        . "</div>"
                ;

                $headers = 'MIME-Version: 1.0' . "\r\n";
                $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
                $mail = wp_mail($to, $subject, $content, $headers);
				$arg = array(
                    'status'    => 'success',
                    'message'   => __('Submit successfull', $config['theme_name'])
                );
				echo json_encode($arg);die;
            }
        }

    }

}
?>